<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Refresh, Menu, Upload, Search } from '@element-plus/icons-vue'
import { querySupplierPageApi, deleteSupplierByIdApi, addSupplierApi, updateSupplierApi, querySupplierByIdApi } from '@/api/supplier'
import { queryAllCityApi } from '@/api/city'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const supplierInfo = ref([])
const supplierFrom = ref({ name: '' })
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增供应商')
const formRef = ref()
const form = ref({
  id: '',
  supplierName: '',
  cityCode: '',
  provinceId: '',
  address: '',
  linkName: '',
  linkPhone: '',
  createBy: 'admin',
  is_del: 1 
})

// 城市数据及配置
const cityOptions = ref([])
const cityProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
  emitPath: true,
  expandTrigger: 'hover'
}

const cascaderValue = ref([])

// 获取供应商数据
const getSupplierAll = async () => {
  try {
    const result = await querySupplierPageApi(supplierFrom.value.name, page.value, pageSize.value)
    supplierInfo.value = result.data.list
      // .filter(item => item.is_del == 1 ||item.isDel)
      // .map(item => ({
      //   ...item,
      //   createBy: item.createBy || '系统'
      // }))
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取供应商数据失败')
  }
}

// 获取城市数据
const getCityData = async () => {
  try {
    const result = await queryAllCityApi()
    if (result.code === 200) {
      cityOptions.value = result.data
    } else {
      ElMessage.error('城市数据加载失败')
    }
  } catch (error) {
    ElMessage.error('获取城市数据失败')
  }
}

// 城市名称格式化
const formatCityName = (row) => {
  if (row.cityName) return row.cityName
  
  const findPath = (id, options, path = []) => {
    for (const item of options) {
      if (item.id === id) return [...path, item.name]
      if (item.children) {
        const found = findPath(id, item.children, [...path, item.name])
        if (found) return found
      }
    }
    return null
  }
  
  const path = row.cityCode ? findPath(row.cityCode, cityOptions.value) : null
  return path ? path.join('-') : '未知城市'
}

// 城市选择变更处理
const handleCityChange = (valueArray) => {
  if (valueArray?.length === 3) {
    form.value.provinceId = valueArray[0]
    form.value.cityCode = valueArray[2]
  } else {
    form.value.provinceId = ''
    form.value.cityCode = ''
    ElMessage.warning('请完整选择省、市、区三级')
  }
}

// 新增供应商
const addSupplier = () => {
  dialogTitle.value = '新增供应商'
  form.value = {
    id: '',
    supplierName: '',
    cityCode: '',
    provinceId: '',
    address: '',
    linkName: '',
    linkPhone: '',
    createBy: 'admin',
    is_del: 1,
    createTime: new Date().toISOString()
  }
  cascaderValue.value = []
  dialogVisible.value = true
}

// 编辑供应商
const edit = async (id) => {
  try {
    const result = await querySupplierByIdApi(id)
    if (result.code) {
      dialogTitle.value = '编辑供应商'
      form.value = result.data
      
      if (form.value.cityCode) {
        const findPath = (id, options, path = []) => {
          for (const item of options) {
            if (item.id === id) return [...path, item.id]
            if (item.children) {
              const found = findPath(id, item.children, [...path, item.id])
              if (found) return found
            }
          }
          return []
        }
        cascaderValue.value = findPath(form.value.cityCode, cityOptions.value)
      }
      
      dialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取供应商信息失败')
  }
}

// 删除供应商
const deleteById = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该供应商吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const result = await deleteSupplierByIdApi(id)
    if (result.code) {
      ElMessage.success('删除成功')
      getSupplierAll()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    if (!form.value.cityCode || !form.value.provinceId) {
      ElMessage.warning('请完整选择省、市、区三级')
      return
    }
    
    if (!form.value.id) {
      form.value.is_del = 1
      form.value.createTime = new Date().toISOString()
    }
    
    form.value.updateTime = new Date().toISOString()
    
    const result = form.value.id 
      ? await updateSupplierApi(form.value)
      : await addSupplierApi(form.value)
    
    if (result.code) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      getSupplierAll()
    }
  } catch (error) {
    if (error !== 'validate') {
      ElMessage.error('操作失败')
    }
  }
}

// 分页事件
const handleSizeChange = (val) => {
  page.value = 1
  pageSize.value = val
  getSupplierAll()
}

const handleCurrentChange = (val) => {
  page.value = val
  getSupplierAll()
}

// 初始化
onMounted(async () => {
  await getCityData()
  getSupplierAll()
})
</script>

<template>
  <!-- 顶部操作栏 - 圆形图标按钮+搜索框 -->
  <div class="page-header">
    <div class="action-buttons">
      <el-tooltip content="新增供应商" placement="bottom">
        <el-button class="circle-button" type="primary" @click="addSupplier" circle>
          <el-icon><Plus /></el-icon>
        </el-button>
      </el-tooltip>
      
      <el-tooltip content="刷新数据" placement="bottom">
        <el-button class="circle-button" @click="getSupplierAll" circle>
          <el-icon><Refresh /></el-icon>
        </el-button>
      </el-tooltip>
      
      <el-tooltip content="列表视图" placement="bottom">
        <el-button class="circle-button" circle>
          <el-icon><Menu /></el-icon>
        </el-button>
      </el-tooltip>
      
      <el-tooltip content="导入数据" placement="bottom">
        <el-button class="circle-button" circle>
          <el-icon><Upload /></el-icon>
        </el-button>
      </el-tooltip>
    </div>
    
    <!-- 右侧搜索框 -->
    <div class="search-box">
      <el-input
        v-model="supplierFrom.name"
        placeholder="供应商名称"
        clearable
        @keyup.enter="getSupplierAll"
      >
        <template #append>
          <el-button type="primary" @click="getSupplierAll" :icon="Search" />
        </template>
      </el-input>
    </div>
  </div>
  
  <!-- 数据表格 -->
  <div><h3>供应商管理</h3></div>
  <div class="table-container">
    <el-table :data="supplierInfo" border style="width: 100%">
      <el-table-column type="index" label="序号" align="center" width="60" />
      <el-table-column prop="supplierName" label="供应商名称" align="center" />
      <el-table-column label="所在城市" align="center">
        <template #default="{row}">
          {{ formatCityName(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="详细地址" align="center" />
      <el-table-column prop="linkName" label="负责人" align="center" />
      <el-table-column prop="linkPhone" label="联系方式" align="center" />
      <el-table-column prop="createBy" label="创建人" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="160" />
      <el-table-column prop="updateTime" label="最后更新时间" align="center" width="160" />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row.id)">修改</el-button>
          <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form ref="formRef" :model="form" label-width="100px">
      <el-form-item label="供应商名称" prop="supplierName" required>
        <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />
      </el-form-item>
      <el-form-item label="所在城市" prop="cityCode" required>
        <el-cascader
          v-model="cascaderValue"
          :options="cityOptions"
          :props="cityProps"
          @change="handleCityChange"
          placeholder="请选择省、市、区"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address" required>
        <el-input v-model="form.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="负责人" prop="linkName" required>
        <el-input v-model="form.linkName" placeholder="请输入负责人姓名" />
      </el-form-item>
      <el-form-item label="联系方式" prop="linkPhone" required>
        <el-input v-model="form.linkPhone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="创建人" v-if="form.id">
        <el-input v-model="form.createBy" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.circle-button {
  width: 40px;
  height: 40px;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-box {
  width: 300px;
}

.search-box :deep(.el-input-group__append) {
  padding: 0 12px;
}

.table-container {
  margin-top: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 优化级联选择器样式 */
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-cascader-menu) {
  min-width: 120px;
}
</style>